package com.fannnnn.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fannnnn.system.pojo.LoginUser;
import com.fannnnn.system.pojo.User;
import com.fannnnn.system.service.LoginService;
import com.fannnnn.system.service.UserService;
import com.fannnnn.system.utils.JwtUtil;
import com.fannnnn.system.utils.RedisUtil;
import com.fannnnn.system.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * \*  Created with IntelliJ IDEA.
 * \*  @author shensifan
 * \*  Date: 2022/1/26
 * \*  Time: 15:30
 * \*  Description:
 * \
 */


@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    AuthenticationManager authenticationManager;

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    UserServiceImpl userService;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Override
    public Result login(User user) {

        /**
         * 使用authenticationManager进行认证
         * */

        UsernamePasswordAuthenticationToken authenticationToken
                = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        /**
         * 对认证结果进行判定
         * */

        //如果认证失败
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("用户不存在！");
        }

        //生成jwt
        /**
         * token:。。。。。。
         * */
        LoginUser loginUser= (LoginUser) authenticate.getPrincipal();
        Long id = loginUser.getUser().getId();
        String jwt = JwtUtil.createJWT(id.toString());
        Map<String,String> map = new HashMap<>();
        map.put("token",jwt);

        /**
         * todo  将用户信息存到redis当中
         * */
        redisUtil.set("User:"+id,loginUser);

        //返回结果
        return new Result(200,"认证成功",jwt);
    }


    /**
     * 注册接口，密码加密
     * */
    @Override
    public Result register(User user) {

        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name",user.getUserName());
        User oldUser = userService.getOne(wrapper);
        if(!Objects.isNull(oldUser)){
            throw new RuntimeException("该用户已注册!");
        }

        User newUser = new User();
        newUser.setUserName(user.getUserName());
        newUser.setPassword(passwordEncoder.encode(user.getPassword()));

        userService.save(newUser);

        return new Result(200,"注册成功",newUser);
    }

    @Override
    public Result logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User user = (User) authentication.getPrincipal();
        Long userid = user.getId();
        redisUtil.del("User:"+userid);
        return new Result(200,"注销成功",null);
    }

}
